package tronglv.gs.view;

import java.util.ArrayList;
import java.util.Random;
import java.util.Stack;

import org.andengine.engine.camera.Camera;
import org.andengine.entity.Entity;
import org.andengine.entity.sprite.AnimatedSprite;
import org.andengine.entity.sprite.Sprite;
import org.andengine.entity.util.FPSLogger;
import org.andengine.extension.physics.box2d.FixedStepPhysicsWorld;
import org.andengine.extension.physics.box2d.PhysicsWorld;
import org.andengine.input.touch.TouchEvent;
import org.andengine.opengl.texture.region.TiledTextureRegion;
import org.andengine.opengl.util.GLState;

import tronglv.gs.animation.anijewelpurple;
import tronglv.gs.control.SceneManager;
import tronglv.gs.model.BaseScene;
import tronglv.gs.model.Jewel;
import tronglv.gs.model.Share;
import android.util.Log;
import android.widget.Toast;

import com.badlogic.gdx.math.Vector2;

public class playScene extends BaseScene {
	private int w, h;
	private PhysicsWorld mPhysicsWorld;
	private Sprite chessBoard, sTitle, sTimeProcess, sTimeLevel, sBestScore,
			sScore, sPause;
	private anijewelpurple animChoose, aEliminate_green, aEliminate_blue,
			aEliminate_yellow, aEliminate_red, aEliminate_purple,
			aEliminate_oranges, aEliminate_row, aEliminate_column,
			aEliminate_lighting, aCombo, aFire, aNormalScore,
			aNormalScoreEffect;
	Random random;
	private boolean[][] tempJewel;
	private AnimatedSprite[][] animJewel;
	Entity mEntity, mEtChoice;
	boolean isChoose, canEat = false;

	Jewel[][] arrJewel;
	Stack<Jewel> eatenJewle = new Stack<Jewel>();
	Stack<Integer> eatenXPos = new Stack<Integer>();
	Stack<Integer[]> canEatenPos = new Stack<Integer[]>();

	@Override
	public void createScene() {
		w = Share.width;
		h = Share.height;
		camera.setCenter(w / 2, h / 2);
		mEntity = new Entity();
		mEtChoice = new Entity();
		random = new Random();
		arrJewel = new Jewel[9][7];
		// tempJewel = new boolean[9][7];
		animJewel = new AnimatedSprite[9][7];
		creatPlay();
		draw();
		engine.registerUpdateHandler(new FPSLogger());
		this.mPhysicsWorld = new FixedStepPhysicsWorld(30, new Vector2(0, 0),
				false, 8, 1);
		this.registerUpdateHandler(this.mPhysicsWorld);
	}

	public void creatPlay() {
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 7; j++) {
				int a = Share.randomInteger(0, 5, random);
				arrJewel[i][j] = new Jewel(j, i);
				arrJewel[i][j].setTypeJewel(a);
				arrJewel[i][j].setIsEated(false);
				// tempJewel[i][j] = false;
			}
		}
	}

	public TiledTextureRegion randJewel(int i) {
		TiledTextureRegion a = null;
		switch (i) {
		case 0:
			a = resourcesManager.jewelGreen_region;
			break;
		case 1:
			a = resourcesManager.jewelRed_region;
			break;
		case 2:
			a = resourcesManager.jewelBlue_region;
			break;
		case 3:
			a = resourcesManager.jewelYellow_region;
			break;
		case 4:
			a = resourcesManager.jewelPurple_region;
			break;
		case 5:
			a = resourcesManager.jewelOranges_region;
			break;
		}

		return a;

	}

	public Jewel getJewle(int x, int y) {
		if (x >= 7 || y >= 9) {
			return null;
		}

		return arrJewel[y][x];
	}

	public boolean checkCanEatJew(int x, int y) {
		ArrayList<Integer> temp_ngang = new ArrayList<Integer>();
		ArrayList<Integer> temp_doc = new ArrayList<Integer>();

		// xet ngang
		int count = 0;
		int startPoint = 0 - x < -2 ? -2 : 0 - x;
		int endPoint = 7 - x > 3 ? 3 : 7 - x;

		for (int a = startPoint; a < endPoint; a++) {
			if (arrJewel[x][y] == arrJewel[x][y + a]) {
				temp_ngang.add(a);
				count++;
			} else if (count >= 2) {
				for (int k = 0; k < temp_ngang.size(); k++) {
					// tempJewel[x][y + temp_ngang.get(k)] = true;
					arrJewel[x][y + temp_ngang.get(k)].setIsEated(true);
					canEatenPos
							.push(new Integer[] { x, y + temp_ngang.get(k) });
				}
				canEat = true;
			} else {
				count = 0;
				temp_ngang.clear();
			}

		}
		// xet doc
		startPoint = 0 - y < -2 ? -2 : 0 - y;
		endPoint = 9 - y > 3 ? 3 : 9 - y;

		for (int a = startPoint; a < endPoint; a++) {
			if (arrJewel[x][y] == arrJewel[x + a][y]) {
				temp_doc.add(a);
				count++;
			} else if (count >= 2) {
				for (int k = 0; k < temp_doc.size(); k++) {
					arrJewel[x+ temp_ngang.get(k)][y ].setIsEated(true);
					canEatenPos
							.push(new Integer[] { x+ temp_ngang.get(k), y  });
				}
				canEat = true;

			} else {
				count = 0;
				temp_doc.clear();
			}

		}
		return canEat;
	}

	// xet xem vien kim cuong nao an duoc thi cho = -1
	public void eatJewel() {
		// for (int i = 0; i < 9; i++) {
		// for (int j = 0; j < 7; j++) {
		// if (arrJewel[i][j].getIsEated()) {
		// arrJewel[i][j].setIsEated(false);
		// eatenJewle.push(arrJewel[i][j]);
		// eatenXPos.push(j);
		// }
		// }
		// }
		while (!canEatenPos.empty()) {
			Integer[] pos = canEatenPos.pop();
			eatenJewle.push(arrJewel[pos[1]][pos[0]]);
			eatenXPos.push(pos[0]);
		}
	}

	// tao vien kim cuong moi
	public void generateNewJewel() {
		while (!eatenJewle.empty()) {
			Jewel eaten = eatenJewle.pop();
			for (int i = eaten.getY(); i >= 0; i--) {
				if (!arrJewel[eaten.getX()][i].getIsEated()) {
					eaten.setY(i);
					arrJewel[eaten.getX()][i].setY(eaten.getyLast());
				}
			}
		}

		generateRandomLostJewel();
	}

	// tao random nhung vien kim cuong them vao
	public void generateRandomLostJewel() {
		while (!eatenXPos.empty()) {
			int x = eatenXPos.pop();

			int stopY = 0;
			while (arrJewel[stopY][x].getIsEated()) {
				stopY++;
			}

			while (arrJewel[0][x].getIsEated()) {
				arrJewel[0][x] = new Jewel(x, 0);

				arrJewel[0][x].setY(arrJewel[stopY - 1][x].getY());
				arrJewel[stopY - 1][x].setY(arrJewel[0][x].getyLast());
				stopY--;
			}
		}
	}

	public void draw() {
		attachChild(new Sprite(0, 0, resourcesManager.play_bg_region, vbom) {
			@Override
			protected void preDraw(GLState pGLState, Camera pCamera) {
				super.preDraw(pGLState, pCamera);
				pGLState.enableDither();
			}
		});

		chessBoard = new Sprite(10, 71,
				resourcesManager.play_chessBoard_region, vbom);
		this.attachChild(chessBoard);
		sTitle = new Sprite(0, 60, resourcesManager.title_separator_region,
				vbom);
		this.attachChild(sTitle);

		sTimeProcess = new Sprite(0, 65 + chessBoard.getHeight(),
				resourcesManager.level_process_region, vbom);
		this.attachChild(sTimeProcess);

		sTimeLevel = new Sprite(60, 70 + chessBoard.getHeight(), 400, 20,
				resourcesManager.level_time_process_region, vbom);
		this.attachChild(sTimeLevel);

		sScore = new Sprite(50, 5, resourcesManager.score_region, vbom);
		this.attachChild(sScore);

		sBestScore = new Sprite(150, 3, resourcesManager.best_score_region,
				vbom);
		this.attachChild(sBestScore);

		sPause = new AnimatedSprite(390, 5, resourcesManager.pause_region, vbom);
		this.attachChild(sPause);

		// draw Jewel & create event
		for (int i = 0; i < 9; i++) {
			for (int j = 0; j < 7; j++) {
				// arrJewel[i][j].setA(randJewel());
				animJewel[i][j] = new AnimatedSprite(10 + 66 * j, 70 + 66 * i,
						66, 66, randJewel(arrJewel[i][j].getTypeJewel()), vbom) {
					@Override
					public boolean onAreaTouched(TouchEvent pSceneTouchEvent,
							float pTouchAreaLocalX, float pTouchAreaLocalY) {
						switch (pSceneTouchEvent.getAction()) {
						case TouchEvent.ACTION_DOWN:
							if (!isChoose) {
								isChoose = true;
								animChoose.setX(this.getX());
								animChoose.setY(this.getY());
								mEtChoice.attachChild(animChoose);

							} else {
								animChoose.setX(this.getX());
								animChoose.setY(this.getY());
							}
							break;

						case TouchEvent.ACTION_MOVE:
							if (!isChoose) {
								isChoose = true;
								animChoose.setX(this.getX());
								animChoose.setY(this.getY());
								mEtChoice.attachChild(animChoose);
							} else {
								animChoose.setX(this.getX());
								animChoose.setY(this.getY());
							}
						default:
							break;
						}

						return super.onAreaTouched(pSceneTouchEvent,
								pTouchAreaLocalX, pTouchAreaLocalY);
					}
				};

				this.attachChild(animJewel[i][j]);
				this.registerTouchArea(animJewel[i][j]);
				if (checkCanEatJew(i, j)) {
					Log.d("Loi", "True");

				}
			}
		}
		// draw select a jewel
		animChoose = new anijewelpurple(animJewel[0][0].getWidth() / 2
				- resourcesManager.play_select_region.getWidth() / 2,
				animJewel[0][0].getHeight() / 2
						- resourcesManager.play_select_region.getHeight() / 2,
				66, 66, resourcesManager.play_select_region, vbom, 0, 1);
		this.attachChild(mEtChoice);
	}

	@Override
	public void onBackKeyPressed() {
		try {
			SceneManager.getInstance().loadPlaytoMenu();
		} catch (Exception e) {
			activity.runOnUiThread(new Runnable() {
				public void run() {
					Toast.makeText(activity,
							"Thao tác bị lỗi vui lòng thử lại",
							Toast.LENGTH_SHORT).show();
				}
			});
		}
	}
}
